package com.jstyle.jclife.utils;

import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v4.content.FileProvider;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.ExerciseHistoryActivity;
import com.jstyle.jclife.activity.SharePreviewActivity;
import com.jstyle.jclife.view.ShareBottomView;
import com.jstyle.jclife.view.ShareDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2017/3/22.
 */

public class ScreenUtils {
    private static final String TAG = "ScreenUtils";

    public static void showSetSuccessFul(View view){
        Context context=view.getContext();
        Snackbar snackbar=Snackbar.make(view,context.getString(R.string.Successful),Snackbar.LENGTH_SHORT);
        View mView=snackbar.getView();
        mView.setBackgroundColor(context.getResources().getColor(R.color.dialog_bg_color));
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(mView.getLayoutParams().width,mView.getLayoutParams().height);
        params.gravity = Gravity.CENTER;
        params.setMargins(dip2px(context,16),0,dip2px(context,16),0);
        mView.setLayoutParams(params);
        TextView tvSnackbarText = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
        tvSnackbarText.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);;
        tvSnackbarText.setGravity(Gravity.CENTER);
        snackbar.show();
    }
    public static void showSetSuccessFul(View view,String msg){
        Context context=view.getContext();
        Snackbar snackbar=Snackbar.make(view,msg,Snackbar.LENGTH_SHORT);
        View mView=snackbar.getView();
        mView.setBackgroundColor(context.getResources().getColor(R.color.dialog_bg_color));
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(mView.getLayoutParams().width,mView.getLayoutParams().height);
        params.gravity = Gravity.CENTER;
        params.setMargins(dip2px(context,16),0,dip2px(context,16),0);
        mView.setLayoutParams(params);
        TextView tvSnackbarText = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
        tvSnackbarText.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);;
        tvSnackbarText.setGravity(Gravity.CENTER);
        snackbar.show();
    }
    public static void setSwitchColor(SwitchCompat v) {

        // thumb color
        int thumbColor = Color.WHITE;
        int thumbColorChecked = 0xffb4bd00;

        // trackColor
        int trackColor = 0xffb3c1c5;
        int trackColorChecked = 0xc0b4bd00;

        // set the thumb color
        DrawableCompat.setTintList(v.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        thumbColorChecked,
                       thumbColor
                }));

        // set the track color
        DrawableCompat.setTintList(v.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        trackColorChecked,
                        trackColor
                }));
    }


    public static void setDialogButtonTextColor(AlertDialog alertDialog) {
        Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        if (button != null) button.setTextColor(Color.WHITE);
        Button buttonCancel = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        if (buttonCancel != null) buttonCancel.setTextColor(Color.WHITE);

    }

    public static void setButtonTextColor(TimePickerDialog alertDialog) {
        Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        if (button != null) button.setTextColor(Color.WHITE);
        Button buttonCancel = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        if (buttonCancel != null) buttonCancel.setTextColor(Color.WHITE);
//        TextView textView=alertDialog.findViewById(com.android.internal.R.id.top_label);
//        if(textView!=null)textView.setTextColor(Color.WHITE);
    }

    public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        int resourceId = 0;
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid != 0) {
            resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");

            return context.getResources().getDimensionPixelSize(resourceId);
        } else
            return 0;
    }
        public static void setStatusBarColor(ViewGroup viewGroup, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            viewGroup.setVisibility(View.VISIBLE);
            viewGroup.setBackgroundColor(color);
            viewGroup.getLayoutParams().height = getStatusBarHeight(viewGroup.getContext());
        }
    }



    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     *
     * @param
     * @return
     */
//    public static String snapShotWithoutStatusBar(Activity activity) {
//        View view = activity.getWindow().getDecorView();
//        view.setDrawingCacheEnabled(true);
//        view.buildDrawingCache();
//        Bitmap bmp = view.getDrawingCache();
//        Rect frame = new Rect();
//        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//        int statusBarHeight = frame.top;
//
//        int width = getScreenWidth(activity);
//        int height = getScreenHeight(activity);
//        Bitmap bp = null;
//        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
//                - statusBarHeight);
//        view.destroyDrawingCache();
//        return saveShotPic(bp);
//
//    }
    public static String saveShotPic(Bitmap bm,String filePath) {
        String shotPath = "";
        try {
            String path = ImageUtils.shootPath;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            File bitfile = new File(path+filePath);
            if (!bitfile.exists()) {
                bitfile.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(bitfile);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            shotPath = bitfile.getAbsolutePath();

        } catch (Exception e) {
            // TODO: handle exception
        }
        return shotPath;
    }
//    public static String getBitmapByView(ViewGroup scrollView) {
//
//     // scrollView.destroyDrawingCache();
//        //return saveShotPic(bitmap);
//    }

    public static void scrollDown(final ScrollView scrollView) {

        scrollView.post(new Runnable() {
            @Override
            public void run() {
                //  scrollViewDataDay.fullScroll(ScrollView.FOCUS_DOWN);
                scrollView.smoothScrollTo(0, scrollView.getChildAt(0).getMeasuredHeight());
            }
        });
    }

    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (scale * spValue);
    }
    /**
     * 将px值转换为sp值，保证文字大小不变
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    public static float getFontHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }

    public static void setTitleTypeface(TextView textView) {
        Context context = textView.getContext();
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "ROBOTO-MEDIUM.TTF");
        textView.setTypeface(typeface);
    }
    public static void setBigTitleTypeface(TextView textView) {
        Context context = textView.getContext();
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "Brandon_bld.otf");
        textView.setTypeface(typeface);
    }

    public static void setTitleTypeface(Button button) {
        Context context = button.getContext();
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "ROBOTO-MEDIUM.TTF");
        button.setTypeface(typeface);
    }

    /**直接分享不带二维码
     * @param context
     * @param viewGroup
     */
    public static void shareFile(final Context context, ViewGroup viewGroup) {
        ShareBottomView shareBottomView=new ShareBottomView(context);
        Bitmap bitmapShare=shareBottomView.getBitmap();
        int h = bitmapShare.getHeight();
        int width = viewGroup.getWidth();
        for (int j = 0; j < viewGroup.getChildCount(); j++) {
            h += viewGroup.getChildAt(j).getHeight();
        }
        final  Bitmap bitmap = Bitmap.createBitmap(width, h, Bitmap.Config.ARGB_8888);
         Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(context.getResources().getColor(R.color.main_bg_color));
        viewGroup.draw(canvas);
        canvas.drawBitmap(bitmapShare,0,h-bitmapShare.getHeight(),null);
        final String path=System.currentTimeMillis()+".jpg";
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                saveShotPic(bitmap,path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                shareFile(context,path);
            }
        });

    }
    public static void shareFile(final Context context, ViewGroup viewGroup, final String date) {
        ShareBottomView shareBottomView=new ShareBottomView(context);
        Bitmap bitmapShare=shareBottomView.getBitmap();
        int h = bitmapShare.getHeight();
        int width = viewGroup.getWidth();
        for (int j = 0; j < viewGroup.getChildCount(); j++) {
            h += viewGroup.getChildAt(j).getHeight();
        }
        final  Bitmap bitmap = Bitmap.createBitmap(width, h, Bitmap.Config.ARGB_8888);
         Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(context.getResources().getColor(R.color.main_bg_color));
        viewGroup.draw(canvas);
        canvas.drawBitmap(bitmapShare,0,h-bitmapShare.getHeight(),null);
        final String path=date+".jpg";
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                saveShotPic(bitmap,path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                toShare(context,path,date,"","");
            }
        });

    }
    public static void shareFile(final Context context,final Bitmap bitmap) {
        final String path=System.currentTimeMillis()+".jpg";
        ShareBottomView shareBottomView=new ShareBottomView(context);
        final Bitmap bitmapShare=shareBottomView.getBitmap();
        final Bitmap bitmapCanvas=Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight()+bitmapShare.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmapCanvas);
        canvas.drawBitmap(bitmap,0,0,null);
        canvas.drawBitmap(bitmapShare,0,bitmap.getHeight(),null);
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                saveShotPic(bitmapCanvas,path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                shareFile(context,path);
                //toShare(context,path);
                bitmapShare.recycle();
                bitmap.recycle();
            }
        });

    }
    public static void shareMapFile(final Context context, Bitmap bitmapMap, final Bitmap timeBitmap, ViewGroup viewGroup, final String date,final String fastPace,final String lastPace) {

        final ProgressDialog    progressDialog = new ProgressDialog(context,R.style.appprogressdialog);
        progressDialog.setMessage(context.getString(R.string.wait));
        progressDialog.show();
        ShareBottomView shareBottomView=new ShareBottomView(context);
        final Bitmap bitmapShare=shareBottomView.getBitmap();
        int h = bitmapShare.getHeight();
        int width = viewGroup.getWidth();
        for (int j = 0; j < viewGroup.getChildCount(); j++) {
            h += viewGroup.getChildAt(j).getHeight();
        }
        final  Bitmap bitmap = Bitmap.createBitmap(width, h, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        viewGroup.draw(canvas);
        int topMargin=ScreenUtils.dip2px(context,0);
        canvas.drawBitmap(bitmapMap,0,0,null);
        canvas.drawBitmap(timeBitmap,0,0,null);

        canvas.drawBitmap(bitmapShare,0,h-bitmapShare.getHeight(),null);
        final String path=date+"1.jpg";

        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                saveShotPic(bitmap,path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
                progressDialog.dismiss();
            }

            @Override
            public void onComplete() {
               //shareFile(context,path);
                toShare(context,path,date,fastPace,lastPace);
                bitmapShare.recycle();
                bitmap.recycle();
                timeBitmap.recycle();
                progressDialog.dismiss();
            }
        });

    }

    private static void shareFile(Context context,String path){
//        ShareDialog shareDialog=new ShareDialog(context,R.style.MyDialogStyle,path);
//        shareDialog.show();
        shareByPhone(context,path);
    }
    private static void toShare(Context context,String path,String date,final String fastPace,final String lastPace){
       Intent intent=new Intent(context, SharePreviewActivity.class);
       intent.putExtra(SharePreviewActivity.sharePicture_Path,path);
       intent.putExtra(SharePreviewActivity.share_FastPace,fastPace);
       intent.putExtra(SharePreviewActivity.share_lowstPace,lastPace);
       intent.putExtra(ExerciseHistoryActivity.pathRecordDate,date);
       context.startActivity(intent);
    }
    public static void shareByPhone(Context context,String path){
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    context.getString(R.string.fileprovider), new File(ImageUtils.shootPath+path));
        } else {
            imageUri = Uri.fromFile(new File(ImageUtils.shootPath+path));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/*");
        context.startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    public static Spannable getSpannable(String text, String startText, int textSize) {
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, textSize);
        return kcalSpannable;
    }

    public static void setSizeSpannable(Spannable word, int start, int end, int textSize) {
        word.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }


}
